package net.aramzamzam.tapestry.judo.components;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.aramzamzam.tapestry.judo.services.Require;

import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.SupportsInformalParameters;
import org.apache.tapestry5.ioc.internal.util.InternalUtils;
import org.apache.tapestry5.json.JSONObject;



/**
 * A component used to collect a provided date from the user using a client-side JavaScript calendar. Non-JavaScript
 * clients can simply type into a text field.
 * <p/>
 * One wierd aspect here is that, because client-side JavaScript formatting and parsing is so limited, we (currently)
 * use Ajax to send the user's input to the server for parsing (before raising the popup) and formatting (after closing
 * the popup).  Wierd and inefficient, but easier than writing client-side JavaScript for that purpose.
 */
// TODO: More testing; see https://issues.apache.org/jira/browse/TAPESTRY-1844
@Require(TimeTextBox.DOJO_TYPE)
@SupportsInformalParameters
public class TimeTextBox extends ConstraintsTextBox<Date>
{
    public static final String DOJO_TYPE="dijit.form.TimeTextBox";
	private static final SimpleDateFormat fmt=new SimpleDateFormat("'T'HH:mm:ss");
    
    /**
     * The format used to format <em>and parse</em> dates. This is typically specified as a string which is coerced to a
     * DateFormat. You should be aware that using a date format with a two digit year is problematic: Java (not
     * Tapestry) may get confused about the century.
     */
    @Parameter(required = true, allowNull = false, defaultPrefix = BindingConstants.LITERAL)
    private DateFormat format;
    
    private static final String TIME_FORMAT_CONSTRAINT = "timePattern";

    DateFormat defaultFormat()
    {
        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("HH:mm");

        return simpleDateFormat;
    }

  	@Override
	protected String getClientValue(Date value) {
		if (value == null) return "";
        return fmt.format(value);
	}

	@Override
	protected JSONObject getConstraints() {
	    JSONObject jContraints=new JSONObject();
	    jContraints.put(TIME_FORMAT_CONSTRAINT, ((SimpleDateFormat)format).toPattern());
		return jContraints;
	}

	@Override
	protected String getDojoType() {
		return DOJO_TYPE;
	}

	@Override
	protected Date getServerValue(String value) throws ValidationException {
		try
        {
            if (InternalUtils.isNonBlank(value))
                return (Date)fmt.parse(value);
            return null;
        }
        catch (ParseException ex)
        {
            throw new ValidationException(ex.getMessage());
        }
	}
}
